package net.pingfang.devicelock;

import lombok.extern.slf4j.Slf4j;
import net.pingfang.devicelock.Config.DecoderFactory;
import net.pingfang.devicelock.constant.PacketDecoder;
import net.pingfang.devicelock.util.DeviceDecodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.Arrays;
import java.util.concurrent.*;


@Slf4j
@Service
public class AsyncHandler {

    private final ThreadPoolTaskExecutor taskExecutor;


    private final DecoderFactory decoderFactory;


    @Autowired  // 当有多个同名Bean时需显式指定
    public AsyncHandler(@Qualifier("tcpTaskExecutor") ThreadPoolTaskExecutor tcpTaskExecutor,
                        DecoderFactory decoderFactory) {
        this.taskExecutor = tcpTaskExecutor;
        this.decoderFactory = decoderFactory;
    }

    /**
     * 分类解析
     * 1.在无发送请求时，电子锁设备回自动上传数据
     * 2.主动向电子锁发送请求报文时，回接收到电子锁返回信息
     * 都是同一个端口、需要解析的内容不一致
     * 如何根据报文内容分别进入不同的解码函数？
     * 是不是使用redis存储设备code
     */
    @Async("tcpTaskExecutor")  // 指定线程池
    public void process(byte[] bys) {
            // 业务逻辑（如解析报文、数据库操作）
            if(bys == null || bys.length < 6  ){
                log.info("空字节异常===>{}", "接收TCP报文为空");
                return ;
            }
            // 自定义业务逻辑（如解析 JSON、持久化数据等）将数据通过websocket上传到vue
            try {
                log.info("bys==>{}",bys);
                PacketDecoder<?> packetDecoder =  decoderFactory.getDecoder(DeviceDecodeUtil.
                        bytesToHex(bys,1,3));
                if(packetDecoder == null){
                    log.info("当前输入报文未做解码解析");
                    return;
                }
                packetDecoder.decode(bys);
            } catch (Exception e) {
                log.error("AsyncHandler类异常==》{}",e.getMessage());
            }
    }

    public void hhd_process(byte[] payload) {

        CompletableFuture.runAsync(() -> log.info("回传报文======{}", Arrays.toString(payload)));

    }

    /**
     * 接收阅读器与上位机报文
     * 没收到消息的原因: 要跟阅读器做一个对接
     *
     */
        /**
        * 发送TCP请求并获取响应（线程安全）
        */




}